<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>应用程序健康检查</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 20px;
            background-color: #f5f7fa;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .test-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .test-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        
        .test-buttons button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        
        .btn-primary { background: #007bff; color: white; }
        .btn-success { background: #28a745; color: white; }
        .btn-warning { background: #ffc107; color: #212529; }
        .btn-danger { background: #dc3545; color: white; }
        
        .result {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            border-left: 4px solid #007bff;
            margin-top: 15px;
        }
        
        .result.success {
            border-left-color: #28a745;
            background: #d4edda;
        }
        
        .result.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
        
        .result pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }
        
        .status-online { background: #28a745; }
        .status-offline { background: #dc3545; }
        .status-unknown { background: #ffc107; }
    </style>
</head>
<body>
    <div class="header">
        <h1>🔍 应用程序健康检查</h1>
        <p>检查后端服务是否正常运行</p>
    </div>

    <!-- 服务状态 -->
    <div class="test-section">
        <h3>🌐 服务状态</h3>
        <div id="serviceStatus">
            <span class="status-indicator status-unknown"></span>
            <span>检查中...</span>
        </div>
        <button class="btn-primary" onclick="checkServiceHealth()">🔄 刷新状态</button>
    </div>

    <!-- 基础API测试 -->
    <div class="test-section">
        <h3>🔧 基础API测试</h3>
        <div class="test-buttons">
            <button class="btn-primary" onclick="testLogin()">🔐 测试登录</button>
            <button class="btn-success" onclick="testProjects()">📊 测试项目API</button>
            <button class="btn-warning" onclick="testUsers()">👥 测试用户API</button>
            <button class="btn-danger" onclick="testDashboard()">📈 测试仪表盘API</button>
        </div>
        <div id="testResult"></div>
    </div>

    <!-- 数据库连接测试 -->
    <div class="test-section">
        <h3>🗄️ 数据库连接测试</h3>
        <button class="btn-primary" onclick="testDatabase()">测试数据库连接</button>
        <div id="dbResult"></div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080';
        let token = '';

        // 页面加载时自动检查服务状态
        window.onload = function() {
            checkServiceHealth();
        };

        // 检查服务健康状态
        async function checkServiceHealth() {
            const statusDiv = document.getElementById('serviceStatus');
            
            try {
                const response = await fetch(`${API_BASE}/actuator/health`, {
                    method: 'GET',
                    timeout: 5000
                });
                
                if (response.ok) {
                    statusDiv.innerHTML = `
                        <span class="status-indicator status-online"></span>
                        <span>✅ 服务正常运行 (端口 8080)</span>
                    `;
                } else {
                    statusDiv.innerHTML = `
                        <span class="status-indicator status-offline"></span>
                        <span>❌ 服务响应异常 (HTTP ${response.status})</span>
                    `;
                }
            } catch (error) {
                // 如果actuator不可用，尝试其他端点
                try {
                    const response = await fetch(`${API_BASE}/auth/login`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ username: 'test', password: 'test' })
                    });
                    
                    // 即使登录失败，但能收到响应说明服务是运行的
                    statusDiv.innerHTML = `
                        <span class="status-indicator status-online"></span>
                        <span>✅ 服务正常运行 (端口 8080)</span>
                    `;
                } catch (innerError) {
                    statusDiv.innerHTML = `
                        <span class="status-indicator status-offline"></span>
                        <span>❌ 服务离线或端口8080不可访问</span>
                    `;
                }
            }
        }

        // 测试登录
        async function testLogin() {
            try {
                const response = await fetch(`${API_BASE}/auth/login`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username: 'sbxnh', password: '123456' })
                });

                if (response.ok) {
                    const data = await response.json();
                    token = data.token;
                    localStorage.setItem('token', token);
                    showResult('✅ 登录测试成功', data, 'success');
                } else {
                    const errorText = await response.text();
                    showResult('❌ 登录测试失败', { status: response.status, error: errorText }, 'error');
                }
            } catch (error) {
                showResult('❌ 登录测试网络错误', { error: error.message }, 'error');
            }
        }

        // 测试项目API
        async function testProjects() {
            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    showResult('❌ 请先登录', { error: '需要先执行登录测试' }, 'error');
                    return;
                }
            }

            try {
                const response = await fetch(`${API_BASE}/projects`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    showResult('✅ 项目API测试成功', { 
                        projectCount: data.length,
                        projects: data.slice(0, 2) // 只显示前2个项目
                    }, 'success');
                } else {
                    const errorText = await response.text();
                    showResult('❌ 项目API测试失败', { status: response.status, error: errorText }, 'error');
                }
            } catch (error) {
                showResult('❌ 项目API测试网络错误', { error: error.message }, 'error');
            }
        }

        // 测试用户API
        async function testUsers() {
            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    showResult('❌ 请先登录', { error: '需要先执行登录测试' }, 'error');
                    return;
                }
            }

            try {
                const response = await fetch(`${API_BASE}/users`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    showResult('✅ 用户API测试成功', { 
                        userCount: data.length,
                        users: data.map(u => ({ id: u.id, username: u.username, fullName: u.fullName }))
                    }, 'success');
                } else {
                    const errorText = await response.text();
                    showResult('❌ 用户API测试失败', { status: response.status, error: errorText }, 'error');
                }
            } catch (error) {
                showResult('❌ 用户API测试网络错误', { error: error.message }, 'error');
            }
        }

        // 测试仪表盘API
        async function testDashboard() {
            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    showResult('❌ 请先登录', { error: '需要先执行登录测试' }, 'error');
                    return;
                }
            }

            try {
                const response = await fetch(`${API_BASE}/dashboard/data`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    showResult('✅ 仪表盘API测试成功', { 
                        userSummary: data.userSummary,
                        projectCount: data.projectStatistics?.totalProjects || 0,
                        taskCount: data.taskStatistics?.totalTasks || 0
                    }, 'success');
                } else {
                    const errorText = await response.text();
                    showResult('❌ 仪表盘API测试失败', { status: response.status, error: errorText }, 'error');
                }
            } catch (error) {
                showResult('❌ 仪表盘API测试网络错误', { error: error.message }, 'error');
            }
        }

        // 测试数据库连接
        async function testDatabase() {
            if (!token) {
                token = localStorage.getItem('token');
                if (!token) {
                    showDbResult('❌ 请先登录', { error: '需要先执行登录测试' }, 'error');
                    return;
                }
            }

            try {
                // 通过获取用户列表来测试数据库连接
                const response = await fetch(`${API_BASE}/users`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const data = await response.json();
                    showDbResult('✅ 数据库连接正常', { 
                        message: '成功从数据库获取数据',
                        recordCount: data.length
                    }, 'success');
                } else {
                    showDbResult('❌ 数据库连接测试失败', { status: response.status }, 'error');
                }
            } catch (error) {
                showDbResult('❌ 数据库连接测试网络错误', { error: error.message }, 'error');
            }
        }

        // 显示测试结果
        function showResult(title, data, type = 'info') {
            const resultDiv = document.getElementById('testResult');
            const className = type === 'success' ? 'result success' : (type === 'error' ? 'result error' : 'result');
            
            resultDiv.innerHTML = `
                <div class="${className}">
                    <h4>${title}</h4>
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                </div>
            `;
        }

        // 显示数据库测试结果
        function showDbResult(title, data, type = 'info') {
            const resultDiv = document.getElementById('dbResult');
            const className = type === 'success' ? 'result success' : (type === 'error' ? 'result error' : 'result');
            
            resultDiv.innerHTML = `
                <div class="${className}">
                    <h4>${title}</h4>
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                </div>
            `;
        }
    </script>
</body>
</html>
